package com.cslg.questionnaires.controller;

import com.cslg.questionnaires.entity.Question;
import com.cslg.questionnaires.entity.Student;
import com.cslg.questionnaires.entity.Teacher;
import com.cslg.questionnaires.service.HomeService;
import com.cslg.questionnaires.utils.JsonMsgBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class StudentHomeController {
    @Autowired
    private HomeService homeService;

    @GetMapping("/StudentHome")
    public ModelAndView teacherPage(@RequestParam("page") int page, HttpSession session){
        Student student = (Student) session.getAttribute("user");
        String userType = (String) session.getAttribute("userType");
        int studentId = student.getId();

        String username = student.getStu_name();
        String account = student.getStu_id();
        Map<String,Object> serviceMsg = homeService.getMyQuestionsById(studentId,page,userType);
        int code = (int)serviceMsg.get("code");

        HashMap<String, Object> data = new HashMap<>();
        data.put("userType",userType);
        data.put("username",username);
        data.put("account",account);
        if (code == 400){
            return new ModelAndView("Home",data);
        }else{
            List<Question> questionStateList = (List<Question>) serviceMsg.get("data");
            if (questionStateList.size() != 0)
                data.put("questionStateList",questionStateList);
            return new ModelAndView("Home",data);
        }
    }

    @PostMapping("/StudentHome/delete")
    @ResponseBody
    public HashMap<String,Object> deleteQuestion(@RequestBody HashMap<String,Object> request, HttpSession session){
        Teacher teacher = (Teacher)session.getAttribute("user");
        String userType = (String) session.getAttribute("userType");
        int userid = teacher.getId();
        int questionid = Integer.parseInt((String) request.get("deleteid"));

        Map<String,Object> msg = homeService.delMyQuestionByid(questionid,userid,userType);
        int code = (int)msg.get("code");
        if (code == 200) {
            return JsonMsgBuilder.jsonBuild(200, "success");
        } else {
            return JsonMsgBuilder.jsonBuild(500,"服务器错误，请稍后重试！");
        }
    }
}
